export default {

  upperInitial(str) {
    return str[0].toUpperCase() + str.slice(1)
  },

	attr({size}) {
		let obj = {}
		if (size) {
			['fontSize', 'width', 'height']
				.forEach(v => obj[v] = `${size}px`)
		}
		return obj
	},

  throttle: createThrottle(),

  getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
      return {
        start: input.selectionStart,
        end: input.selectionEnd
      };
    }
    else if (input.createTextRange) {
      var sel = document.selection.createRange();
      if (sel.parentElement() === input) {
        var rng = input.createTextRange();
        rng.moveToBookmark(sel.getBookmark());
        for (var len = 0;
            rng.compareEndPoints("EndToStart", rng) > 0;
            rng.moveEnd("character", -1)) {
          len++;
        }
        rng.setEndPoint("StartToStart", input.createTextRange());
        for (var pos = { start: 0, end: len };
            rng.compareEndPoints("EndToStart", rng) > 0;
            rng.moveEnd("character", -1)) {
          pos.start++;
          pos.end++;
        }
        return pos;
      }
    }
    return -1;
  }
}

function createThrottle() {
  var prev;
  var timeout;
  var clear;
  var defaultMin = 600;
  return (fn, min) => {
    min = min || defaultMin;
    var now = new Date().getTime();
    if (timeout) {
      clearTimeout(timeout);
    }
    if(prev) {
      clearTimeout(clear);
      if (now - prev >= min) {
        clearTimeout(timeout);
        //console.log('run');
        fn();
      } else {
        timeout = setTimeout(() => {
          //console.log('timeout run');
          fn();
        }, min);
      }
    } else {
      timeout = setTimeout(() => {
        //console.log('first timeout run');
        fn();
      }, min);
    }
    prev = now;
    clear = setTimeout(() => {
      //console.log('clear');
      prev = false;
      clearTimeout(timeout);
    }, min);
  }
}
